<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Observer
 *
 * @author ketu
 */
class Zhishidi_Dailydeals_Model_Observer {
    const XML_DAILYDEALS_SETTINGS_MODEL_PATH = 'zhishidi_dailydeals/settings';
    const XML_DAILYDEALS_DEALS_MODEL_PATH = 'zhishidi_dailydeals/deals';

    protected function getDeailyDealsProductIds() {
        $_dailyDealsCollection = Mage::getModel(self::XML_DAILYDEALS_DEALS_MODEL_PATH)->getCollection()
                        ->joinProducts()->addVisibleFilter()
                        ->addStoreFilter(Mage::app()->getStore(true)->getStoreId())
                        ->setDateRange(date('Y-m-d H:i:s', Mage::app()->getLocale()->storeTimeStamp()))
                        ->addFieldToFilter('deal_ended', array('null' => true));
        #echo $_dailyDealsCollection->getSelect()->__toString();
        $productIds = array();
        $dataArray = array();
        if (($_dailyDealsCollection->count())) {
            foreach ($_dailyDealsCollection as $deal) {
                $productIds[] = $deal->getProductId();
                $dataArray[$deal->getProductId()] = array(
                    'deal' => $deal->getId(),
                    'from' => $deal->getDealFrom(),
                    'to' => $deal->getDealTo(),
                    'total' => $deal->getDealTotal(),
                    'limit' => $deal->getDealLimit(),
                    'price' => $deal->getDealPrice(),
                );
            }
        }
        return array('id' => $productIds, 'data' => $dataArray);
    }

    public function addProductToCart($observer) {
        if (!Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->isEnabled())
            return $this;
        $items = Mage::getSingleton('checkout/cart')->getQuote()->getAllItems();
        $event = $observer->getEvent();
        $product = $event->getProduct();
        #$quote_item = $event->getQuoteItem();

        $dailydeals = $this->getDeailyDealsProductIds();
        if (in_array($product->getId(), $dailydeals['id'])) {
            $left_stock = $dailydeals['data'][$product->getId()]['limit'];
            if (Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->isCookiesEnabled()) {
                $exists = Mage::getSingleton('core/cookie')->get(Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->getCookiesPrefix($dailydeals['data'][$product->getId()]['deal']));
                if ((int) $exists >= $dailydeals['data'][$product->getId()]['limit']) {
                    return $this;
                } else {
                    $left_stock = (int) $exists;
                }
            }
            foreach ($items as $item) {
                if ($item['product_id'] == $product->getId()) {
                    #echo $product->getQty();
                    if ($dailydeals['data'][$item['product_id']]['limit'] > 0 && $product->getQty() > $dailydeals['data'][$item['product_id']]['limit']) {
                        $limit = $dailydeals['data'][$item['product_id']]['limit'] >= $dailydeals['data'][$item['product_id']]['total'] ? $dailydeals['data'][$item['product_id']]['total'] : $dailydeals['data'][$item['product_id']]['limit'];
                        $limit = $limit >= $left_stock ? $left_stock : $limit;
                        $item->setQty($limit);
                        $item->save();
                        //$quote_item->setOriginalCustomPrice(199.00);
                        /*
                          $quote_item->setQty($limit);
                          $quote_item->calcRowTotal();
                          $quote_item->save();
                         *
                         */
                    }
                }
            }
        }
        return $this;
    }

    public function changeDailyDealTotal($observer) {
        if (!Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->isEnabled())
            return true;
        $order = $observer->getOrder();
        $items = $order->getAllItems();
        $dailydeals = $this->getDeailyDealsProductIds();

        foreach ($items as $item) {
            $product = $item->getProduct();
            if (in_array($product->getId(), $dailydeals['id'])) {
                if (Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->isCookiesEnabled()) {
                    $exists = Mage::getSingleton('core/cookie')->get(Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->getCookiesPrefix($dailydeals['data'][$product->getId()]['deal']));
                    if ((int) $exists >= $dailydeals['data'][$product->getId()]['limit']) {
                        continue;
                    }
                }

                $deal = Mage::getModel(self::XML_DAILYDEALS_DEALS_MODEL_PATH)->load($dailydeals['data'][$product->getId()]['deal']);
                $stock = $deal->getDealTotal();
                $left_stock = (int) $stock - (int) $item->getQtyOrdered() > 0 ? (int) $stock - (int) $item->getQtyOrdered() : 0;
                $deal->setDealTotal($left_stock);
                $deal->setDealEnded(date('Y-m-d H:i:s', Mage::app()->getLocale()->storeTimeStamp()));
                $deal->save();
                if (Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->isCookiesEnabled()) {
                    $exists = (int) Mage::getSingleton('core/cookie')->get(Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->getCookiesPrefix($deal->getId()));
                    $exists += (int) $item->getQtyOrdered();
                    Mage::getSingleton('core/cookie')->set(Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->getCookiesPrefix($deal->getId()), $exists, Mage::app()->getLocale()->storeTimeStamp() + (int) Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->getCookiesTtl());
                }
                #$cookies->set('zhishidi_dailydeals_da');
            }
        }
    }

    public function changeProductPrice($observer) {
        if (!Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->isEnabled())
            return $this;
        $product = $observer->getEvent()->getProduct();

        $dailydeals = $this->getDeailyDealsProductIds();

        if (in_array($product->getId(), $dailydeals['id'])) {

            if (Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->isCookiesEnabled()) {
                $exists = Mage::getSingleton('core/cookie')->get(Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->getCookiesPrefix($dailydeals['data'][$product->getId()]['deal']));
                if ((int) $exists >= $dailydeals['data'][$product->getId()]['limit']) {
                    return $this;
                }
            }
            $product->setFinalPrice($dailydeals['data'][$product->getId()]['price']);
        }
        return $this;
    }

    public function changeProductQty($observer) {
        if (!Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->isEnabled())
            return true;
        $dailydeals = $this->getDeailyDealsProductIds();

        $event = $observer->getEvent();
        $cart = $event->getCart();
        $data = $event->getInfo();

        foreach ($data as $itemId => $itemInfo) {
            $item = $cart->getQuote()->getItemById($itemId);
            if (!$item) {
                continue;
            }
            if (in_array($item['product_id'], $dailydeals['id'])) {
                $left_stock = $dailydeals['data'][$item['product_id']]['limit'];
                if (Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->isCookiesEnabled()) {
                    $exists = Mage::getSingleton('core/cookie')->get(Mage::getModel(self::XML_DAILYDEALS_SETTINGS_MODEL_PATH)->getCookiesPrefix($dailydeals['data'][$item['product_id']]['deal']));
                    if ((int) $exists >= $dailydeals['data'][$item['product_id']]['limit']) {
                        continue;
                    } else {
                        $left_stock = (int) $exists;
                    }
                }
                if ($dailydeals['data'][$item['product_id']]['limit'] > 0 && $itemInfo['qty'] > $dailydeals['data'][$item['product_id']]['limit']) {
                    $limit = $dailydeals['data'][$item['product_id']]['limit'] >= $dailydeals['data'][$item['product_id']]['total'] ? $dailydeals['data'][$item['product_id']]['total'] : $dailydeals['data'][$item['product_id']]['limit'];
                    $limit = $limit >= $left_stock ? $left_stock : $limit;
                    $item->setQty($limit);
                    $item->save();
                }
            }
        }
    }

}

?>
